# encoding: utf-8
"""
Database models
--------------------
"""
from sqlalchemy_utils import Timestamp

from app.extensions import db

from app.modules.common.utils import JsonEncoder
class Zone(db.Model, Timestamp, JsonEncoder):
    """ database model. """
    zone_code = db.Column(db.String(32), primary_key=True)  # 唯一标示
    parent_code = db.Column(db.String(32), nullable=True)  # 指向父级zone，大的zone包含小的zone
    zone_title = db.Column(db.String(32), nullable=True)  # 标题
    zone_desc = db.Column(db.String(128), nullable=True)  # 描述
    available = db.Column(db.Boolean, nullable=True)  # 是否激活（部署）；当build_in属性为true时，available必须为true
    home_path = db.Column(db.String(256), nullable=True)  # zone内所有应用部署的根路径
    build_in = db.Column(db.Boolean, nullable=True)  # 是否内建，内建表示默认强制初始化
    timezone = db.Column(db.String(32), nullable=True)  #
    zone_alias = db.Column(db.String(64), nullable=True)  #
    order_no = db.Column(db.Integer, nullable=True)  #

    def __init__(self, zone_code, parent_code=None, zone_title=None, zone_desc=None, available=False,
                 home_path=None, build_in=False, timezone=None, zone_alias=None, order_no=None):
        self.zone_code = zone_code
        self.parent_code = parent_code
        self.zone_title = zone_title
        self.zone_desc = zone_desc
        self.available = available
        self.home_path = home_path
        self.build_in = build_in
        self.timezone = timezone
        self.zone_alias = zone_alias
        self.order_no = order_no

    def __repr__(self):
        return (
            "<{class_name}("
            "zone_code={self.zone_code}, "
            "parent_code=\"{self.parent_code}\", "
            "zone_title=\"{self.zone_title}\", "
            "zone_desc=\"{self.zone_desc}\", "
            "available=\"{self.available}\", "
            "home_path=\"{self.home_path}\", "
            "build_in=\"{self.build_in}\", "
            "timezone=\"{self.timezone}\", "
            "zone_alias=\"{self.zone_alias}\", "
            "order_no=\"{self.order_no}\", "
            ")>".format(
                class_name=self.__class__.__name__,
                self=self
            )
        )

    @db.validates(('build_in', 'available'))
    def validate_available(self, key, build_in, available):
        if build_in and not available:
            raise ValueError("invalid available, [build_in] equal to True, [available] must be equal to True.")

        return available
